import React, { useState, useRef, useEffect } from 'react';
import { Tag, Icon, Input } from 'antd';

// value: []
const TagNames = React.forwardRef(({
    value = [],
    onChange,
    addButtonName = '添加工作要点',
    disabled,
    maxLength = 5,
    onErr,
    onSucc
}, ref) => {
    const [inputVisible, setInputVisible] = useState(false);
    const [inputValue, setInputValue] = useState('');
    const input = useRef(null);
    const handleClose = (item, e) => {
        e.preventDefault();
        const findIndex = value.findIndex(val => val === item);

        onChange([...value.slice(0, findIndex), ...value.slice(findIndex + 1)]);
        onSucc([...value.slice(0, findIndex), ...value.slice(findIndex + 1)]);
    };
    const handleInputConfirm = () => {
        // 如果input有输入 &输入长度2+ &不存在相同内容=存入
        if (
            inputValue &&
            inputValue.length > 1 &&
            value.indexOf(inputValue) === -1
        ) {
            onChange([...value, inputValue]);
            onSucc([...value, inputValue]);
        } else {
            // 调用此函数，让父组件显示错误信息
            onErr(value);
        }
        setInputVisible(false);
        setInputValue('');
    };
    useEffect(() => {
        if (inputVisible) {
            input.current.focus();
        }
    }, [inputVisible]);
    return (
        <div ref={ref}>
            {Array.isArray(value) &&
                value.map(item => (
                    <Tag
                        key={item}
                        closable
                        onClose={e => handleClose(item, e)}
                    >
                        {item}
                    </Tag>
                ))}
            {inputVisible && (
                <Input
                    ref={input}
                    type="text"
                    size="small"
                    style={{ width: '20em' }}
                    maxLength={50}
                    value={inputValue}
                    onChange={e => setInputValue(e.target.value)}
                    onBlur={handleInputConfirm}
                    onPressEnter={handleInputConfirm}
                />
            )}
            {!disabled && !inputVisible && value.length < maxLength && (
                <Tag
                    onClick={() => setInputVisible(true)}
                    style={{ background: '#fff', borderStyle: 'dashed' }}
                >
                    <Icon type="plus" /> {addButtonName}
                </Tag>
            )}
        </div>
    );
})

export default TagNames;
